<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-select
              v-model="filters.departmentId"
              placeholder="选择部门"
              style="width: 150px"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
            <el-select
              v-model="filters.contractorId"
              placeholder="选择承包商"
              style="width: 150px"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="contractor in contractors"
                :key="contractor.id"
                :label="contractor.name"
                :value="contractor.id"
              />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或昵称"
              style="width: 200px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="filteredUsers" v-loading="loading">
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="电话" width="140" />
        <el-table-column prop="employeeNumber" label="工号" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="departmentName" label="部门" width="150">
          <template #default="{ row }">
            <el-tag v-if="row.departmentName" type="primary" size="small">
              {{ row.departmentName }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractorName" label="承包商" width="150">
          <template #default="{ row }">
            <el-tag v-if="row.contractorName" type="warning" size="small">
              {{ row.contractorName }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" min-width="200">
          <template #default="{ row }">
            <div class="roles-container">
              <el-tag
                v-for="role in row.roles"
                :key="role"
                size="small"
                :type="getRoleTagType(role)"
                class="role-tag"
              >
                {{ getRoleName(role) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="formData.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeNumber">
              <el-input v-model="formData.employeeNumber" placeholder="请输入工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="departmentId">
              <el-select v-model="formData.departmentId" placeholder="请选择部门" clearable>
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属承包商" prop="contractorId">
              <el-select v-model="formData.contractorId" placeholder="请选择承包商" clearable>
                <el-option
                  v-for="contractor in contractors"
                  :key="contractor.id"
                  :label="contractor.name"
                  :value="contractor.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="用户角色" prop="roles">
          <el-checkbox-group v-model="formData.roles">
            <div class="role-categories">
              <div class="role-category">
                <h4>系统角色</h4>
                <el-checkbox
                  v-for="role in systemRoles"
                  :key="role.code"
                  :value="role.code"
                >
                  {{ role.name }}
                </el-checkbox>
              </div>
              <div class="role-category">
                <h4>业务角色</h4>
                <el-checkbox
                  v-for="role in businessRoles"
                  :key="role.code"
                  :value="role.code"
                >
                  {{ role.name }}
                </el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入初始密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useDepartmentStore } from '@/stores/department'
import { useContractorStore } from '@/stores/contractor'
import { useRoleStore } from '@/stores/role'
import type { User, UserForm, Department, Contractor, Role } from '@/types'

const userStore = useUserStore()
const departmentStore = useDepartmentStore()
const contractorStore = useContractorStore()
const roleStore = useRoleStore()

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref<FormInstance>()

const users = ref<User[]>([])
const departments = ref<Department[]>([])
const contractors = ref<Contractor[]>([])
const roles = ref<Role[]>([])
const currentUser = ref<User | null>(null)

const filters = reactive({
  departmentId: undefined as number | undefined,
  contractorId: undefined as number | undefined
})

const formData = reactive<UserForm>({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  status: 'active',
  roles: [],
  departmentId: undefined,
  contractorId: undefined,
  employeeNumber: '',
  position: ''
})

const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 过滤后的用户列表
const filteredUsers = computed(() => {
  let result = users.value

  if (searchKeyword.value) {
    result = result.filter(user =>
      user.username.includes(searchKeyword.value) ||
      user.nickname.includes(searchKeyword.value)
    )
  }

  if (filters.departmentId) {
    result = result.filter(user => user.departmentId === filters.departmentId)
  }

  if (filters.contractorId) {
    result = result.filter(user => user.contractorId === filters.contractorId)
  }

  return result
})

// 系统角色
const systemRoles = computed(() => {
  return roles.value.filter(role => role.type === 'system')
})

// 业务角色
const businessRoles = computed(() => {
  return roles.value.filter(role => role.type === 'business')
})

// 获取角色名称
const getRoleName = (roleCode: string) => {
  const role = roles.value.find(r => r.code === roleCode)
  return role ? role.name : roleCode
}

// 获取角色标签类型
const getRoleTagType = (roleCode: string) => {
  const role = roles.value.find(r => r.code === roleCode)
  if (!role) return 'info'
  
  if (role.type === 'system') return 'primary'
  if (role.code.includes('authority')) return 'warning'
  if (role.code.includes('approver')) return 'danger'
  if (role.code.includes('safety')) return 'success'
  return 'info'
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const [usersList, deptsList, contractorsList, rolesList] = await Promise.all([
      userStore.getAllUsers(),
      departmentStore.getAllDepartments(),
      contractorStore.getAllContractors(),
      roleStore.getAllRoles()
    ])
    users.value = usersList
    departments.value = deptsList
    contractors.value = contractorsList
    roles.value = rolesList
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑在computed中处理
}

// 过滤
const handleFilter = () => {
  // 过滤逻辑在computed中处理
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  currentUser.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: User) => {
  isEdit.value = true
  currentUser.value = row
  Object.assign(formData, {
    username: row.username,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    status: row.status,
    roles: [...row.roles],
    departmentId: row.departmentId,
    contractorId: row.contractorId,
    employeeNumber: row.employeeNumber || '',
    position: row.position || '',
    password: '' // 编辑时不显示密码
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.nickname}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.deleteUser(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 编辑时不需要验证密码
    if (isEdit.value) {
      delete formData.password
    }
    
    if (isEdit.value && currentUser.value) {
      await userStore.updateUser(currentUser.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await userStore.createUser(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    status: 'active',
    roles: [],
    departmentId: undefined,
    contractorId: undefined,
    employeeNumber: '',
    position: ''
  })
  formRef.value?.resetFields()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.user-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
    
    .roles-container {
      .role-tag {
        margin-right: 4px;
        margin-bottom: 4px;
      }
    }
  }
  
  .role-categories {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    
    .role-category {
      margin-bottom: 16px;
      
      h4 {
        margin: 0 0 8px 0;
        color: #606266;
        font-size: 14px;
      }
      
      .el-checkbox {
        display: block;
        margin-bottom: 8px;
      }
    }
  }
}
</style>